package com.syh.jn.scm.domain.supplier.entity.stock;

import cn.redscarf.commons.util.validator.ValidationUtils;
import com.syh.core.ddd.domain.AbstractSimpleAggregate;
import com.syh.jn.scm.domain.supplier.entity.base.goods.Goods;
import com.syh.jn.scm.dto.supplier.stock.StockBeginGoodsSto;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

import java.math.BigDecimal;

@Data
@EqualsAndHashCode(callSuper = true)
@NoArgsConstructor
public class StockGoods extends AbstractSimpleAggregate<Long> {

  /**
   * 保存商品
   *
   * @param goods
   */
  public void save(Goods goods) {
    this.goodsId = goods.getId();
    this.name = goods.getName();
    this.code = goods.getCode();
    this.categoryCatalogCode = goods.getCategoryCatalogCode();
    this.categoryId = goods.getCategoryId();
    this.goodsBrandId = goods.getGoodsBrandId();
    this.originId = goods.getOriginId();
    this.manufacturerId = goods.getManufacturerId();
    this.specName = goods.getSpecName();
    this.units = goods.getUnits();
    this.status = goods.getStatus();
    this.conversionRate = goods.getConversionRate();
    this.businessEntityId = goods.getBusinessEntityId();

    this.initDefault();
    this.quantity = BigDecimal.ZERO;
    this.averageCost = BigDecimal.ZERO;
    this.balance = BigDecimal.ZERO;
    this.beginningCount = BigDecimal.ZERO;
    this.beginningAvgUnitPrice = BigDecimal.ZERO;
  }

  /**
   * 修改商品
   *
   * @param goods
   */
  public void update(Goods goods) {
    this.goodsId = goods.getId();
    this.name = goods.getName();
    this.code = goods.getCode();
    this.categoryCatalogCode = goods.getCategoryCatalogCode();
    this.categoryId = goods.getCategoryId();
    this.goodsBrandId = goods.getGoodsBrandId();
    this.originId = goods.getOriginId();
    this.manufacturerId = goods.getManufacturerId();
    this.specName = goods.getSpecName();
    this.units = goods.getUnits();
    this.status = goods.getStatus();
    this.conversionRate = goods.getConversionRate();
    this.lastUpdateTimeStamp = System.currentTimeMillis();
  }

  public void beginningSetUp(StockBeginGoodsSto sto) {
    ValidationUtils.validate(sto);
    this.beginningCount = sto.getBeginningCount();
    this.quantity = sto.getBeginningCount();
    this.beginningAvgUnitPrice = sto.getBeginningAvgUnitPrice();
    this.averageCost = sto.getBeginningAvgUnitPrice();
    this.balance = this.quantity.multiply(averageCost);
  }

//    public void updateStockQuantity(StockRecordItem item) {
//        switch (item.getOrderType()) {
//            //销售退货单
//            case 2:
//            //采购单
//            case 3:
//            //采购退货单
//            case 4:
//            //其他入库单
//            case 7:
//                this.calculateAverageCost(item);
//                return;
//            default:
//                this.quantity = this.quantity.add(item.getQuantity());
//                //如果库存数量不为0 计算库存余额
//                if (this.quantity.compareTo(BigDecimal.ZERO) != 0) {
//                    this.balance = this.balance.add(item.getQuantity().multiply(this.averageCost).setScale(2, BigDecimal.ROUND_HALF_UP));
//                //否则库存余额为0
//                } else {
//                    this.balance = BigDecimal.ZERO;
//                }
//        }
//    }

  public void calculateAverageCost(StockRecordItem item) {
    BigDecimal oldQuantity = this.quantity;
    this.quantity = this.quantity.add(item.getQuantity());
    if (this.quantity.compareTo(BigDecimal.ZERO) != 0) {
      //负库存&零库存出入库以新纪录的成本为准
      if (oldQuantity.compareTo(BigDecimal.ZERO) < 1) {
        this.averageCost = item.getPrice();
        this.balance = this.quantity.multiply(this.averageCost).setScale(2, BigDecimal.ROUND_HALF_UP);
      } else {
        this.balance = this.balance.add(item.getQuantity().multiply(item.getPrice()).setScale(2, BigDecimal.ROUND_HALF_UP));
        this.averageCost = this.balance.divide(this.quantity, 6, BigDecimal.ROUND_HALF_UP);
      }
    }
    //库存为零，成本和库存余额皆为零
    else {
      this.averageCost = BigDecimal.ZERO;
      this.balance = BigDecimal.ZERO;
    }
  }

  /**
   * 商品id
   */
  private Long goodsId;
  /**
   * 商品名称
   */
  private String name;
  /**
   * 编码
   */
  private String code;
  /**
   * 所属种类,应用分类编码
   */
  private String categoryCatalogCode;
  /**
   * 分类id
   */
  private Long categoryId;
  /**
   * 品牌id
   */
  private Long goodsBrandId;
  /**
   * 产地id
   */
  private Long originId;
  /**
   * 生产商id
   */
  private Long manufacturerId;
  /**
   * 规格
   */
  private String specName;
  /**
   * 计量单位
   */
  private String units;
  /**
   * 仓库id
   */
  private Long storehouseId;
  /**
   * 期初数量
   */
  private BigDecimal beginningCount;
  /**
   * 期初均价
   */
  private BigDecimal beginningAvgUnitPrice;
  /**
   * 库存数量
   */
  private BigDecimal quantity;
  /**
   * 平均成本
   */
  private BigDecimal averageCost;
  /**
   * 库存余额
   */
  private BigDecimal balance;
  /**
   * 是否可用: -1停用,1可用
   */
  private Short status;
  /**
   * 与基础商品转换率（如果是基础商品 则等于1）
   */
  private BigDecimal conversionRate;
  /**
   * 归属id
   */
  private Long businessEntityId;
}
